package com.cxq.deadlock;

/**
 * Created by cxq on 2020/7/26.
 */
public class DeadLockRunnable implements Runnable {
    private int flag;//决定线程走向的标记
    //创建两个锁对象,
    //这里一定要加一个static，变成共享资源(临界资源)
    private static Object obj1 = new Object();//锁对象1
    private static Object obj2 = new Object();//锁对象2


    public DeadLockRunnable(int flag) {
        this.flag = flag;
    }

    public void run() {

        if (flag == 1) {
            //线程1执行代码：拥有一个锁对象，去获取另一个锁对象
            synchronized (obj1){
                System.out.println(Thread.currentThread().getName()+"已获取到资源obj1，请求obj2");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj2){
                    System.out.println(Thread.currentThread().getName()+"已经获取到obj1和obj2");
                }
            }
        }else {
            //线程2执行代码
            synchronized (obj2) {
                System.out.println(Thread.currentThread().getName() + "已获取到资源obj1，请求obj2");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj1) {
                    System.out.println(Thread.currentThread().getName() + "已经获取到obj1和obj2");
                }
            }
        }
    }
}
